#!/usr/bin/env python
#
# Copyright (C) 2014-2020 ABINIT Group (Yann Pouillon)
#
# This file is part of the ABINIT software package. For license information,
# please see the COPYING file in the top-level directory of the ABINIT source
# distribution.
#
from __future__ import print_function, division, absolute_import #, unicode_literals

try:
    from ConfigParser import ConfigParser
except ImportError:
    from configparser import ConfigParser
from time import gmtime,strftime

import os
import re
import sys

class MyConfigParser(ConfigParser):

  def optionxform(self,option):
    return str(option)

# ---------------------------------------------------------------------------- #

#
# Subroutines
#

# Makefile header
def makefile_header(name,stamp):

  return """#
# Makefile for ABINIT                                      -*- Automake -*-
#

# Generated by %s on %s

#
# IMPORTANT NOTE
#
# Any manual change to this file will systematically be overwritten.
# Please modify the %s script or its config file instead.
#

#
# If you want to execute a range of tests instead of a whole series, you
# may use the keywords "start", "stop" and "dirname" along with make, e.g.:
#
#    make buildsys start=03 stop=10 dirname=root_name_for_the_test_directory
#
# To execute only one test, just omit either start or stop.
# By default, the dirname is the hostname
#

# Files that must be explicitely removed
DISTCLEANFILES = abichecks.env

# Default host name for test output directories
dirname = `hostname`

# Main test scripts
run_standard_tests = $(BOURNE_SHELL) \\
  $(top_srcdir)/abichecks/scripts/wrap-standard-tests.sh

# Display help by default
all-local: help

help:
	@cat $(top_srcdir)/doc/help_make/help_make_abichecks.txt
""" % (name,stamp,name)



# ---------------------------------------------------------------------------- #

#
# Main program
#

# Initial setup
my_name    = "make-makefiles-abichecks"
my_configs = ["config/specs/abichecks.conf"]
my_output  = "abichecks/Makefile.am"

# Check if we are in the top of the ABINIT source tree
if ( not os.path.exists("configure.ac") or
     not os.path.exists("config/specs/abichecks.conf") ):
  print("%s: You must be in the top of the ABINIT Test Suite source tree." % my_name)
  print("%s: Aborting now." % my_name)
  sys.exit(1)

# Read config file(s)
cnf = MyConfigParser()
for cnf_file in my_configs:
  if ( not os.path.exists(cnf_file) ):
    print("%s: Could not find config file (%s)." % (my_name,cnf_file))
    print("%s: Aborting now." % my_name)
    sys.exit(2)

# What time is it?
now = strftime("%Y/%m/%d %H:%M:%S +0000",gmtime())

# Init
cnf.read(my_configs[0])
abinit_tests = cnf.sections()
abinit_tests.sort()
mf_data = makefile_header(my_name,now)
mf_cln = ""

for series in abinit_tests:

  # Init
  dsc = cnf.get(series,"description")
  if ( cnf.has_option(series,"aliases") ):
    aliases = cnf.get(series,"aliases")
  else:
    aliases = None
  mf_tgt = "tests_%s" % series
  if ( aliases ):
    mf_tgt += " " + aliases

  # Append makefile target
  mf_data += """
# %s
%s:
	@if test ! -e %s; then $(MKDIR_P) %s; fi
	$(run_standard_tests) $(dirname) %s $(start) $(stop)
""" % (dsc,mf_tgt,series,series,series)

  # Append cleaning command
  mf_cln += "\trm -rf %s/tmp-*\n" % (series)

# Prepare clean-local target
mf_data += "\n# Clean-up temporary directories\nclean-local:\n%s" % mf_cln

# Generate EXTRA_DIST information
mf_extra = "EXTRA_DIST ="
xd_data = open("config/dist/auto-abichecks.lst", "rt").read().strip().split("\n")
for src in xd_data:
  mf_extra += " \\\n  %s" % re.sub("^abichecks/","",src)
mf_data += "\n%s\n" % mf_extra

# Write down makefile
mf = open(my_output, "wt")
mf.write(mf_data)
mf.close()
